/*
 * @Copyright: Copyright (c) 2030 吴周海
 * @Author: wzh200x@126.com
 * @Date: 2025-10-13 15:17:08
 * @LastEditors: wzh200x@126.com
 * @LastEditTime: 2025-10-13 15:55:01
 * @FilePath: \gogamewebserver\goGameWebServer\internal\controller\center\center_v1.go
 * @Description: 文件功能描述
 */
package center

import (
	"context"
	"encoding/json"
	v1 "goGameWebServer/api/center/v1"
	"goGameWebServer/internal/controller"
	"goGameWebServer/internal/defines/cerror"
	"goGameWebServer/internal/defines/entityName"
	"goGameWebServer/internal/model/entity"
	"goGameWebServer/internal/register"

	"github.com/gogf/gf/v2/frame/g"
)

func (c *CenterControllerV1) QueryAccount(ctx context.Context, req *v1.QueryAccountReq) (res *v1.QueryAccountRes, err error) {
	centerM := register.GetModel(entityName.EntityName_Center)
	centerD := centerM.GetEntityData().(*entity.CenterModelData)
	centerD.Account = req.AccountName
	e := centerM.LoadEntityDataFromDB(nil)
	if e != nil {
		controller.BackResponseError(nil, cerror.HTTP_ACCOUNT_NOT_FOUND_ERROR,
			cerror.GetErrMsg(cerror.HTTP_ACCOUNT_NOT_FOUND_ERROR))
		return
	}
	res = &v1.QueryAccountRes{}
	if centerD.Data != "" {
		json.Unmarshal([]byte(centerD.Data), &res.Servers)
	}
	controller.BackResponseOK(g.RequestFromCtx(ctx), res)
	return
}

func (c *CenterControllerV1) UpdateAccount(ctx context.Context, req *v1.UpdateAccountReq) (res *v1.UpdateAccountRes, err error) {
	centerM := register.GetModel(entityName.EntityName_Center)
	centerD := centerM.GetEntityData().(*entity.CenterModelData)
	centerD.Account = req.AccountName
	e := centerM.LoadEntityDataFromDB(nil)
	if e != nil {
		controller.BackResponseError(nil, cerror.HTTP_ACCOUNT_NOT_FOUND_ERROR,
			cerror.GetErrMsg(cerror.HTTP_ACCOUNT_NOT_FOUND_ERROR))
		return
	}
	servers := make([]int, 0)
	if centerD.Data != "" {
		json.Unmarshal([]byte(centerD.Data), &servers)
	}
	// 判断servers里面是否已经存在req.ServerID
	for _, v := range servers {
		if v == req.ServerID {
			return
		}
	}
	servers = append(servers, req.ServerID)
	data, _ := json.Marshal(servers)
	centerD.Data = string(data)
	e = centerM.SaveEntityDataToDB()
	if e != nil {
		controller.BackResponseError(nil, cerror.CENTER_UPDATE_ERROR,
			cerror.GetErrMsg(cerror.CENTER_UPDATE_ERROR))
		return
	}
	res = &v1.UpdateAccountRes{}
	res.Servers = servers
	controller.BackResponseOK(g.RequestFromCtx(ctx), res)
	return
}
